import React, {FC, useEffect, useState} from 'react';
import "./index.less";
import {Avatar, Button, Card, Form, Input, message, Space, Tooltip} from "antd";
import {KfBackendEnumPicker, KfModal, KfUpload, useBackendEnum} from "kf-web-library";
import PasswordModifyForm from "@/pages/MinePage/Passport/PasswordModifyForm";
import MobileModifyForm from "@/pages/MinePage/Passport/MobileModifyForm";
import EmailModifyForm from "@/pages/MinePage/Passport/EmailModifyForm";
import {FormattedMessage, useIntl, useModel} from "umi";
import {CloseSquareFilled, UserOutlined} from "@ant-design/icons";
import classNames from "classnames";
import * as API from "@/services";
import {useRequest} from "ahooks";
import {nanoid} from "nanoid";

interface PassportControlItemProps {
  title: React.ReactNode;
  children?: React.ReactNode;
  style?: React.CSSProperties;
  className?: string;
}

const PassportControlItem: FC<PassportControlItemProps> = (props) => {
  const {title, className, children, style} = props;
  return (
    <div className={classNames("passport-control-item", className)} style={style}>
      <div className={"passport-control-item-title"}>{title}</div>
      <div className={"passport-control-item-content"}>{children}</div>
    </div>
  );
};


interface PassportProps {
}


/**
 * 个人设置(安全) 页面
 */
const Passport: FC<PassportProps> = (props) => {
  const {initialState, setInitialState} = useModel('@@initialState');
  const userInfo = initialState?.currentUserInfo;
  const intl = useIntl();

  const {enumDict, enumTypeDict, getBackendEnum} = useBackendEnum();

  const [mobileModifyModalOpen, setMobileModifyModalOpen] = useState(false);
  const [emailModifyModalOpen, setEmailModifyModalOpen] = useState(false);
  const [passwordModifyModalOpen, setPasswordModifyModalOpen] = useState(false);

  const [personalEditable, setPersonalEditable] = useState(false);

  const modifyCurrentUserReq = useRequest((p) => API.modifyCurrentUser(p), {
    manual: true,
    onSuccess: (resp) => {
      if (resp.flag) {
        message.success("个人资料修改成功");
        setPersonalEditable(false);
        initialState?.fetchUserInfo?.().then(u => {
          setInitialState({
            ...initialState,
            currentUserInfo: u,
          })
        })
      }
    }
  })

  const [personalForm] = Form.useForm();

  useEffect(() => {
    personalForm.setFieldsValue({
      nickname: userInfo?.nickname,
      gender: userInfo?.gender,
      avatar: userInfo?.avatar
    });
  }, [userInfo, personalEditable]);

  return (
    <div className={"passport-container"}>
      <Form
        form={personalForm}
        scrollToFirstError={{
          focus: true,
        }}
        className={"tooltip-feedback-form"}
        feedbackIcons={({errors}) => ({
          error: (
            <Tooltip
              key="tooltipKey"
              title={errors?.map((error) => <div key={nanoid()}>{error}</div>)}
              color="red"
            >
              <CloseSquareFilled/>
            </Tooltip>
          ),
        })}
        autoComplete="off"
        onFinish={(values) => {
          modifyCurrentUserReq.run({
            ...values,
          })
        }}>

        <Card
          title={<FormattedMessage id={`mine.PersonalProfile`}/>}
              className={"passport-card"}
        >
          <PassportControlItem title={<FormattedMessage id={`text.avatar`}/>}>
            <div className={"passport-fake-item-wrapper passport-avatar-ct"}>
              {
                personalEditable ? (
                  <Form.Item name={"avatar"} noStyle>
                    <KfUpload.Avatar
                      className={"passport-avatar-upload"}
                      maximumFileSize={2 * 1024 * 1024}
                      maximumFileSizeErrorMessage={"头像图片大小不能超过2M"}
                    />
                  </Form.Item>
                ) : (
                  <div className={"passport-fake"}>
                    <Avatar className={'passport-avatar'} icon={<UserOutlined/>} src={userInfo?.avatar} draggable={false}/>
                  </div>
                )
              }
            </div>
          </PassportControlItem>

          <PassportControlItem title={<FormattedMessage id={`text.nickname`}/>}>
            <div className={"passport-fake-item-wrapper"}>
              {
                personalEditable ? (
                  <Form.Item
                    label={null}
                    messageVariables={{label: intl.formatMessage({id: `text.nickname`})}}
                    name={"nickname"}
                    hasFeedback={true}
                    help=""
                    rules={[
                      {required: true},
                      {
                        pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_\-@.]{1,10}$/,
                        message: intl.formatMessage({id: `validation.nickname_pattern`}),
                      },
                    ]}
                  >
                    <Input
                      /*count={{
                        show: true,
                        max: 10,
                      }}*/
                      placeholder={intl.formatMessage({id: `validation.nickname_require`})}
                      style={{width: 220}}
                    />
                  </Form.Item>
                ) : (
                  <div className={"passport-fake"}>
                    {userInfo?.nickname ?? intl.formatMessage({id: `text.no-set`})}
                  </div>
                )
              }
            </div>
          </PassportControlItem>
          <PassportControlItem title={<FormattedMessage id={`text.gender`}/>}>
            <div className={"passport-fake-item-wrapper"}>
              {
                personalEditable ? (
                  <Form.Item name={"gender"} noStyle rules={[{required: true}]}>
                    <KfBackendEnumPicker.RadioGroup enumType={"Gender"}/>
                  </Form.Item>
                ) : (
                  <div className={"passport-fake"}>
                    {intl.formatMessage({id: `enums.Gender.${userInfo?.gender}`, defaultMessage: getBackendEnum("Gender", userInfo?.gender)?.i18EnumDesc}) ?? intl.formatMessage({id: `text.no-set`})}
                  </div>
                )
              }
            </div>
          </PassportControlItem>
          <PassportControlItem title={""} style={{marginTop: 10}}>
            <Space>
              {
                !personalEditable && (
                  <Button type={"primary"} onClick={() => setPersonalEditable(true)}>
                    <FormattedMessage id={`text.edit`}/>
                  </Button>
                )
              }
              {
                personalEditable && (
                  <>
                    <Button type={"primary"} htmlType={"submit"} loading={modifyCurrentUserReq.loading}>
                      <FormattedMessage id={`text.save`}/>
                    </Button>
                    <Button htmlType={"button"} onClick={() => setPersonalEditable(false)}>
                      <FormattedMessage id={`text.cancel`}/>
                    </Button>
                  </>
                )
              }
            </Space>
          </PassportControlItem>
        </Card>
      </Form>


      <Card
        title={<FormattedMessage id={`mine.AccountAndSecurity`}/>}
            className={"passport-card"}
      >
        <PassportControlItem title={intl.formatMessage({id: `text.bind-mobile`})}>
          <div className={"passport-fake-item-wrapper"}>
            <div className={"passport-fake-item passport-fake-item-has-bg"}>
              {userInfo?.phone ?? intl.formatMessage({id: `text.no-set`})}
            </div>
            <a className={"passport-fake-btn"} onClick={(e) => {
              e.preventDefault();
              setMobileModifyModalOpen(true);
            }}>  {userInfo?.phone ? intl.formatMessage({id: `text.modify`}) : intl.formatMessage({id: `text.set`})}</a>
          </div>
        </PassportControlItem>
        <PassportControlItem title={intl.formatMessage({id: `text.bind-email`})}>
          <div className={"passport-fake-item-wrapper"}>
            <div className={"passport-fake-item passport-fake-item-has-bg"}>
              {userInfo?.email ?? intl.formatMessage({id: `text.no-set`})}
            </div>
            <a className={"passport-fake-btn"} onClick={(e) => {
              e.preventDefault();
              setEmailModifyModalOpen(true);
            }}> {userInfo?.email ? intl.formatMessage({id: `text.modify`}): intl.formatMessage({id: `text.set`})}</a>
          </div>
        </PassportControlItem>
        <PassportControlItem title={intl.formatMessage({id: `mine.PasswordManagement`})}>
          <Space>
            <Button onClick={() => setPasswordModifyModalOpen(true)}>
              <FormattedMessage id={`text.change-pwd`}/>
            </Button>
          </Space>
        </PassportControlItem>
      </Card>


      {
        mobileModifyModalOpen && (
          <KfModal
            className={"passport-modal"}
            title={<FormattedMessage id={`text.change-mobile`}/>}
            open={true}
            destroyOnClose={true}
            onCancel={() => setMobileModifyModalOpen(false)}
            width={600}
            onSubmitted={() => {
              initialState?.fetchUserInfo?.().then(u => {
                setInitialState({
                  ...initialState,
                  currentUserInfo: u,
                })
              })
            }}
          >
            <MobileModifyForm/>
          </KfModal>
        )
      }
      {
        emailModifyModalOpen && (
          <KfModal
            className={"passport-modal"}
            title={<FormattedMessage id={`text.change-email`}/>}
            open={true}
            destroyOnClose={true}
            onCancel={() => setEmailModifyModalOpen(false)}
            width={600}
            onSubmitted={() => {
              initialState?.fetchUserInfo?.().then(u => {
                setInitialState({
                  ...initialState,
                  currentUserInfo: u,
                })
              })
            }}
          >
            <EmailModifyForm/>
          </KfModal>
        )
      }
      {
        passwordModifyModalOpen && (
          <KfModal
            className={"passport-modal"}
            title={<FormattedMessage id={`text.change-pwd`}/>}
            open={true}
            destroyOnClose={true}
            onCancel={() => setPasswordModifyModalOpen(false)}
            onSubmitted={() => {

            }}
            width={600}
          >
            <PasswordModifyForm/>
          </KfModal>
        )
      }
    </div>
  );
};

export default Passport;
